package com.adinnet.admin.common.service.impl;

import com.adinnet.admin.common.service.CommonService;
import com.adinnet.admin.common.shiro.ShiroUtils;
import com.adinnet.admin.common.utils.UserAgentGetter;
import com.adinnet.admin.operation.mapper.OperationMapper;
import com.adinnet.admin.operation.model.Operation;
import com.adinnet.admin.system.model.SysUser;
import com.adinnet.admin.system.model.vo.SysUserInfo;
import com.adinnet.admin.system.model.vo.SysUserRoleVo;
import com.adinnet.admin.system.service.SysUserRoleService;
import com.adinnet.common.utils.StringUtil;
import com.adinnet.core.exception.BizException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 公共 服务实现类
 * </p>
 *
 * @author liukp
 * @since 2020-07-07
 */
@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private OperationMapper operationMapper;

    /**
     * 获取用户信息及权限信息
     * @return
     */
    @Override
    public SysUserInfo getLoginUser(){
        SysUserInfo sysUserInfo=new SysUserInfo();
        SysUser sysUser=ShiroUtils.getLoginUser();
        if(sysUser==null){
            throw new BizException("登录过期，请重新登录");
        }
        BeanUtils.copyProperties(sysUser,sysUserInfo);
        SysUserRoleVo sysUserRoleVo= sysUserRoleService.selectRolesByUserId(sysUser.getId());
        if(sysUserRoleVo!=null && !StringUtil.isBlank(sysUserRoleVo.getRoleCode())){
            sysUserInfo.setRoleNames(sysUserRoleVo.getRoleName());
            sysUserInfo.setRoleCodes(sysUserRoleVo.getRoleCode());
            sysUserInfo.setMaxRole(sysUserRoleVo.getMaxCode());
            sysUserInfo.setMaxRoleSerialNumber(sysUserRoleVo.getMaxSerialNumber());
        }
        log.info("SysUserInfo：{}", JSONObject.toJSONString(sysUserInfo));
        return sysUserInfo;
    }

    /**
     * @description 记录管理端操作日志
     * @author lkp
     * @param
     * @param: operationName
     * @param: request
     * @createTime 2020/12/14 15:55
     */
    @Override
    public void saveOperation(HttpServletRequest request,String operationName){
        if(!StringUtil.isBlank(operationName)){
            SysUserInfo sysUserInfo = getLoginUser();
            UserAgentGetter agentGetter = new UserAgentGetter(request);

            Operation op=new Operation();
            op.setSysUserId(sysUserInfo.getId());
            op.setIpAddress(agentGetter.getIpAddr());
            op.setOperation(operationName);
            operationMapper.insert(op);
        }
    }

}
